<template>
  <div class="app-container">
    <el-card>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="描述:">
          <el-input v-model="queryForm.keyword" placeholder="请输入问题描述" style="width: 200px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
                    @keydown.enter.native="fetchData(1)"
          />
        </el-form-item>
        <el-form-item label="部门:">
          <el-input v-model="queryForm.department" placeholder="请输入部门" style="width: 156px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
                    @keydown.enter.native="fetchData(1)"
          />
        </el-form-item>
        <el-form-item label="类型:">
          <el-input v-model="queryForm.product_type" placeholder="请输入产品类型" style="width: 156px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
                    @keydown.enter.native="fetchData(1)"
          />
        </el-form-item>
        <!--        <el-form-item label="日期范围:">-->
        <!--          <el-date-picker-->
        <!--            v-model="queryForm.dateRange"-->
        <!--            :editable="false"-->
        <!--            style="width: 236px;"-->
        <!--            size="small"-->
        <!--            type="daterange"-->
        <!--            align="right"-->
        <!--            unlink-panels-->
        <!--            value-format="yyyy-MM-dd"-->
        <!--            range-separator="至"-->
        <!--            start-placeholder="开始日期"-->
        <!--            end-placeholder="结束日期"-->
        <!--            :picker-options="pickerOptions"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData(1)">查询</el-button>
        </el-form-item>
        <el-form-item style="flex-grow: 1;" />
        <el-form-item style="margin-right: 0;">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="showNewQuestionDialog()">新建</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        stripe
        highlight-current-row
      >
        <el-table-column align="center" label="编号" width="84">
          <template v-slot="scope">
            {{ scope.row.product_name }}
          </template>
        </el-table-column>
        <el-table-column label="所属部门" width="84">
          <template v-slot="scope">
            {{ scope.row.department }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="手机号" align="center" width="96">-->
        <!--          <template v-slot="scope">-->
        <!--            {{ scope.row.pageviews }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="邮箱" align="center" width="128">-->
        <!--          <template v-slot="scope">-->
        <!--            <span>{{ scope.row.author }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column class-name="status-col" label="产品类型" align="center">
          <template v-slot="scope">
            {{ scope.row.product_type }}
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="工艺类型" align="center">
          <template v-slot="scope">
            {{ scope.row.process_type }}
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="问题描述" align="center">
          <template v-slot="scope">
            {{ scope.row.question_summary }}
          </template>
        </el-table-column>
        <!--        <el-table-column align="center" prop="solved_at" label="处理时间" min-width="65">-->
        <!--          <template v-slot="scope">-->
        <!--            <i class="el-icon-time" />-->
        <!--            <span>{{ scope.row.process_at.slice(0,10) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="记录人" align="center" width="120">
          <template v-slot="scope">
            <span>{{ scope.row.recorder }}</span>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" width="226">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteQuestion(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="pageSize"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="fetchData(currentPage)"
        />
      </div>
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      title="编辑问题"
      :visible.sync="changeQuestionDialog"
      width="90%"
      center
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="编号" prop="product_name">
              <el-input v-model="editForm.product_name" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="department">
              <el-input v-model="editForm.department" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品类型" prop="product_type">
              <el-input v-model="editForm.product_type" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺类型" prop="process_type">
              <el-input v-model="editForm.process_type" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
        <h3>问题描述:</h3>
        <el-row style="border: 1.6px solid #C0C4CC;border-radius: 6px;padding: 12px 24px 0 0;">
          <el-col :span="12">
            <el-form-item label="问题摘要" prop="question_summary">
              <el-input v-model="editForm.question_summary" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :offset="12" />
          <el-col :span="12">
            <el-form-item label="详细描述" prop="question_description">
              <el-input v-model="editForm.question_description" size="mini" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配图上传">
              <div style="display: flex;flex-direction:row;align-items: center;">
                <el-button type="primary" size="mini" @click="upFile2">上传</el-button>
                <el-button v-if="upImg2" type="warning" size="mini" style="margin:auto 24px;" @click="downFile2">清空图片</el-button>
                <input ref="singleFile2" type="file" style="display: none;" @change="handleFileUpload2($event)">
                <!--                <el-image-->
                <!--                  v-if="upImg"-->
                <!--                  style="width: 100px; height: 100px"-->
                <!--                  :src="upURL[0]"-->
                <!--                  :preview-src-list="upURL"-->
                <!--                />-->
                <viewer v-if="upImg2" class="container" :images="upURL2">
                  <img height="100px" width="100px" :src="upURL2[0]" alt="">
                </viewer>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-top: 18px;padding-right: 4px;" label="解决方案" prop="process_method">
          <el-input v-model="editForm.process_method" type="textarea" :rows="3" />
        </el-form-item>
        <!--        <el-form-item label="处理时间" prop="process_at">-->
        <!--          <el-input v-model="questionForm.process_at" type="textarea" :rows="1" />-->
        <!--        </el-form-item>-->
        <el-form-item label="记录人" prop="recorder">
          <el-input v-model="editForm.recorderName" disabled size="mini" style="width: 100px;" />
          <el-button style="margin-left: 12px;" size="mini" type="primary" @click="submitDialogFormVisible = true">选择记录人</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeQuestionDialog = false">取 消</el-button>
        <el-button type="primary" @click="subEditForm('editForm')">立即修改</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="创建新问题"
      style="margin-top:100px;"
      :visible.sync="addQuestionDialog"
      width="90%"
      center
    >
      <el-form ref="registerForm" :model="questionForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="编号" prop="name">
              <el-input v-model="questionForm.name" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="department">
              <el-input v-model="questionForm.department" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品类型" prop="product_type">
              <el-input v-model="questionForm.product_type" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺类型" prop="process_type">
              <el-input v-model="questionForm.process_type" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
        <h3>问题描述:</h3>
        <el-row style="border: 1.6px solid #C0C4CC;border-radius: 6px;padding: 12px 24px 0 0;">
          <el-col :span="12">
            <el-form-item label="问题摘要" prop="summary">
              <el-input v-model="questionForm.summary" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :offset="12" />
          <el-col :span="12">
            <el-form-item label="详细描述" prop="description">
              <el-input v-model="questionForm.description" size="mini" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配图上传">
              <div style="display: flex;flex-direction:row;align-items: center;">
                <el-button type="primary" size="mini" @click="upFile">上传</el-button>
                <el-button v-if="upImg" type="warning" size="mini" style="margin:auto 24px;" @click="downFile">清空图片</el-button>
                <input ref="singleFile" type="file" style="display: none;" @change="handleFileUpload($event)">
                <!--                <el-image-->
                <!--                  v-if="upImg"-->
                <!--                  style="width: 100px; height: 100px"-->
                <!--                  :src="upURL[0]"-->
                <!--                  :preview-src-list="upURL"-->
                <!--                />-->
                <viewer v-if="upImg" class="container" :images="upURL">
                  <img height="100px" width="100px" :src="upURL[0]" alt="">
                </viewer>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-top: 18px;padding-right: 4px;" label="解决方案" prop="method">
          <el-input v-model="questionForm.method" type="textarea" :rows="3" />
        </el-form-item>
        <!--        <el-form-item label="处理时间" prop="process_at">-->
        <!--          <el-input v-model="questionForm.process_at" type="textarea" :rows="1" />-->
        <!--        </el-form-item>-->
        <el-form-item label="记录人" prop="recorder">
          <el-input v-model="questionForm.recorderName" disabled size="mini" style="width: 100px;" />
          <el-button style="margin-left: 12px;" size="mini" type="primary" @click="submitDialogFormVisible = true">选择记录人</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addQuestionDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('registerForm')">立即创建</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择记录人" :visible.sync="submitDialogFormVisible">
      <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
        <!--        <el-form-item>-->
        <!--          <span>该操作将提交工单进入流转状态，请确认工单是否正确填写。</span>-->
        <!--        </el-form-item>-->
        <el-form-item label="记录人:">
          <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                    prefix-icon="el-icon-search"
                    size="small"
                    @keyup.enter.native="searchUser(1)"
          />
          <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px" @click="searchUser(1)">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="searchList"
        style="width: 100%"
      >
        <el-table-column
          label="工号"
          prop="uid"
        />
        <el-table-column
          label="姓名"
          prop="username"
        />
        <el-table-column
          align="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleTo(scope.row.uid,scope.row.username)"
            >设为TA</el-button>
          </template></el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="5"
          background
          layout="prev, pager, next"
          :current-page.sync="dialogCurrentPage"
          :total="dialogTotal"
          @current-change="searchUser(dialogCurrentPage)"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTo($store.getters.userInfo.uid,$store.getters.userInfo.name)">设为自己</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addQuestion, deleteQuestion, getQuestionList, changeQuestion } from '@/api/Question.js'
import { PAGE_SIZES, USER_TYPE_OPTIONS } from '@/utils/common'
import { findUser } from '@/api/user'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      queryUser: {
        keyword: ''
      },
      submitDialogFormVisible: false,
      searchList: [],
      dialogCurrentPage: 1,
      dialogTotal: 0,
      upImg: false,
      upImg2: false,
      options: USER_TYPE_OPTIONS,
      userOptions: USER_TYPE_OPTIONS,
      changeQuestionDialog: false,
      editForm: {},
      upURL: [],
      upURL2: [],
      questionForm: {
        name: '',
        department: '',
        product_type: '',
        process_type: '',
        summary: '',
        description: '',
        method: '',
        recorder: '',
        recorderName: '',
        file: null
      },
      rules: {
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
        product_type: [{ required: true, message: '请输入产品类型', trigger: 'blur' }],
        process_type: [{ required: true, message: '请输入工艺类型', trigger: 'blur' }],
        summary: [{ required: true, message: '请输入问题简介', trigger: 'blur' }],
        description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
        method: [{ required: true, message: '请输入方法', trigger: 'blur' }],
        recorder: [{ required: true, message: '请输入记录人', trigger: 'blur' }]
      }, editRules: {
        product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
        product_type: [{ required: true, message: '请输入产品类型', trigger: 'blur' }],
        process_type: [{ required: true, message: '请输入工艺类型', trigger: 'blur' }],
        question_summary: [{ required: true, message: '请输入问题简介', trigger: 'blur' }],
        question_description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
        process_method: [{ required: true, message: '请输入方法', trigger: 'blur' }],
        recorder: [{ required: true, message: '请输入记录人', trigger: 'blur' }]
      },
      addQuestionDialog: false,
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      queryForm: {
        keyword: '',
        department: '',
        product_type: '',
        status: []
      },
      list: null,
      listLoading: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.fetchData(1)
  },
  methods: {
    handleTo(uid, name) {
      console.log(uid, name)
      if (this.addQuestionDialog) {
        this.questionForm.recorderName = name
        this.questionForm.recorder = uid
      }
      if (this.changeQuestionDialog) {
        this.editForm.recorder = uid
        this.editForm.recorderName = name
      }
      this.submitDialogFormVisible = false
      this.queryUser.keyword = ''
      this.searchList = []
      this.dialogTotal = 0
      // moveOrder(this.queryUser.tid, uid).then(res => {
      //   this.$message({
      //     type: 'success',
      //     message: '流转成功!'
      //   })
      //   this.submitDialogFormVisible = false
      //   this.queryUser.keyword = ''
      //   this.searchUser(1)
      // })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, { name: this.queryUser.keyword }).then(response => {
        this.searchList = response.data.data
        this.dialogTotal = response.data.total
        this.listLoading = false
      })
    },
    upFile() {
      this.$refs.singleFile.click()
    },
    downFile() {
      this.upURL = []
      this.questionForm.file = null
      this.upImg = false
    },
    handleFileUpload(event) {
      event.preventDefault()
      // const formData = new FormData()
      const file = this.$refs.singleFile.files[0]
      this.questionForm.file = file
      console.log(file)
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const that = this
      reader.onload = function(e) {
        console.log(e) // 查看对象属性里面有个result属性，属性值，是一大串的base64格式的东西，这个就是我们要的图片
        console.log(this.result)// 取得数据 这里的this指向FileReader（）对象的实例reader
        that.upURL[0] = this.result
        that.upImg = false
        that.$nextTick(() => {
          that.upImg = true
        })
        // 赋值给img标签让它显示出来
      }
      // formData.append('file', file)
      // this.onUpload(formData)
    },
    upFile2() {
      this.$refs.singleFile2.click()
    },
    downFile2() {
      this.upURL2 = []
      this.editForm.file = null
      this.upImg2 = false
    },
    handleFileUpload2(event) {
      // event.preventDefault()
      // const formData = new FormData()
      console.log(123123)
      const file = this.$refs.singleFile2.files[0]
      this.editForm.file = file
      console.log(file)
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const that = this
      reader.onload = function(e) {
        console.log(e) // 查看对象属性里面有个result属性，属性值，是一大串的base64格式的东西，这个就是我们要的图片
        console.log(this.result)// 取得数据 这里的this指向FileReader（）对象的实例reader
        that.upURL2[0] = this.result
        that.upImg2 = false
        that.$nextTick(() => {
          that.upImg2 = true
        })
        // 赋值给img标签让它显示出来
      }
      // formData.append('file', file)
      // this.onUpload(formData)
    },
    deleteQuestion(item) {
      console.log(item)
      this.$confirm(`此操作将删除${item.product_name}的问题记录, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuestion(item.qid).then(res => {
          this.$message.success('删除成功')
          this.fetchData(1)
        })
      }).catch(() => {
      })
    },
    getFileFromUrl(url, fileName) {
      return new Promise((resolve, reject) => {
        var blob = null
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.setRequestHeader('Accept', 'image/png')
        xhr.responseType = 'blob'
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
          blob = xhr.response
          const file = new File([blob], fileName, { type: 'image/png' })
          // 返回结果
          resolve(file)
        }
        xhr.onerror = (e) => {
          reject(e)
        }
        // 发送
        xhr.send()
      })
    },
    openDialog(info) {
      this.editForm = info
      this.editForm.recorderName = info.recorder_info.username
      this.changeQuestionDialog = true
      if (info.pic) {
        this.upURL2[0] = this.$dict.BASE_API + info.pic
        this.editForm.file = this.getFileFromUrl(this.upURL2[0], 'pic').then(res => {
          this.editForm.file = res
        })
        this.upImg2 = true
      } else {
        this.upImg2 = false
      }
    },
    showNewQuestionDialog() {
      this.addQuestionDialog = true
      // this.$nextTick(() => {
      //   this.$refs['registerForm'].resetFields()
      // })
    },
    subEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const form = new FormData()
          form.append('name', this.editForm.product_name)
          form.append('department', this.editForm.department)
          form.append('product_type', this.editForm.product_type)
          form.append('process_type', this.editForm.process_type)
          form.append('summary', this.editForm.question_summary)
          form.append('description', this.editForm.question_description)
          form.append('method', this.editForm.process_method)
          form.append('recorder', this.editForm.recorder)
          if (this.editForm.file) {
            form.append('file', this.editForm.file)
          } else {
            form.append('file', null)
          }
          changeQuestion(this.editForm.qid, form).then(res => {
            this.$message.success('修改成功！')
            this.changeQuestionDialog = false
            this.fetchData(this.currentPage)
          })
        } else {
          this.$message.error('信息填写不完整，请检查')
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const form = new FormData()
          for (const key in this.questionForm) {
            if (key === 'recorderName') continue
            const data = this.questionForm[key]
            form.append(key, data)
          }
          // form.append('name', this.questionForm.name)
          // form.append('description', this.questionForm.description)
          // form.append('method', this.questionForm.method)
          // form.append('recorder', this.questionForm.recorder)
          addQuestion(form).then(res => {
            this.$message.success('添加成功！')
            this.$refs['registerForm'].resetFields()
            this.addQuestionDialog = false
            this.fetchData(1)
          })
        } else {
          this.$message.error('信息填写不完整，请检查')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    fetchData(page) {
      this.listLoading = true
      const params = {
        // description: this.queryForm.keyword,
        department: this.queryForm.department,
        product_type: this.queryForm.product_type
      }
      if (this.queryForm.keyword) {
        params.description = this.queryForm.keyword
      }
      // if (this.queryForm.status.length === 1) {
      //   params['role'] = this.queryForm.status[0]
      // } else if (this.queryForm.status.length >= 1) {
      //   params['role'] = `(${this.queryForm.status.join()})`
      // }
      getQuestionList(this.pageSize, page, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
        this.currentPage = response.data.page
      })
    },
    viewOrder() {
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  ::v-deep.el-dialog__wrapper{
    margin-top: 0!important;
  }
  ::v-deep.el-dialog{
    margin-top: 6vh!important;
  }
}
.demo-form-inline {
  display: flex;
}
</style>
